package com.sixmac.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.OpenHistory;
import com.sixmac.module.Room;
import com.sixmac.module.Tenant;
import com.sixmac.module.TenantRoom;
import com.sixmac.platform.service.RoomService;
import com.sixmac.util.SMS;
import com.sixmac.utils.Test;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * RoomController
 * 2018-09-11 20:12:57
 *
 * @author Blade
 */
@Controller
@RequestMapping("/lock")
public class LockController extends BaseController {

    @Autowired
    RoomService service;

    @ResponseBody
    @RequestMapping("/myservlet.svl")
    public AjaxResult index(HttpServletRequest request,
                        HttpServletResponse response) {

        try {
            request.setCharacterEncoding("UTF-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            String infoMsg = sb.toString();
            JSONObject json = JSONObject.parseObject(infoMsg);
            System.out.println("aa1111:" + infoMsg);
            String text = json.getString("encrypt");
            String aa = Test.decrypt(text);

            System.out.println("********************start*************************");
            System.out.println(aa);
            json = JSONObject.parseObject(aa);
            System.out.println("********************end*************************");

            //{"direct":1,"fcc":"160323255==","from":1,"magic":1011,"msgid":10060,"type":141,"value":{"result":0,"reason":"ERROR_CODE_OK","lockUserCode":"6"}}

            if(json.containsKey("type")){
                JSONObject value = json.getJSONObject("value");
                if (value.getInteger("result")<100){
                    //指纹录入成功
//                    String msgid = json.getString("msgid");
//                    String lockUserCode = value.getString("lockUserCode");
//                    Integer userId = Integer.valueOf(msgid.substring(3));
//                    String type = msgid.substring(0,3);
//                    if (type.equals("100")){
//                        //房客
//                    }
//                    TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" `status` = 1  and tenantId="+userId,null);
//                    tenantRoom.setFingerprint(Integer.valueOf(lockUserCode));
//                    Blade.create(TenantRoom.class).update(tenantRoom);
                }
                return success("收到");
            }

            String msgType = json.getString("msgType");
            String deviceCode = json.getString("deviceCode");
            String content = null;
            if (msgType.equals("1011")) {
                //是否离在线信息
                content = json.getString("content");
                json = JSONObject.parseObject(content);
                Boolean status = json.getBoolean("online_state");
                Room room = Blade.create(Room.class).findFirstBy(" lockNo='"+deviceCode+"'",null);
                if (room!=null){
                    room.setLockStatus(status?1:0);
                    Blade.create(Room.class).update(room);
                }
            }
            if (msgType.equals("1011")) {
                //是否离在线信息
                content = json.getString("content");
                json = JSONObject.parseObject(content);
                System.out.println(json);

            } else if (msgType.equals("1015")) {
                //定位信息
                content = json.getString("content");
                json = JSONObject.parseObject(content);
                System.out.println(json);

            } else if (msgType.equals("1012")) {
                //剩余电量信息
                content = json.getString("content");
                json = JSONObject.parseObject(content);
                System.out.println(json.getString("power"));
                Room room = Blade.create(Room.class).findFirstBy(" lockNo='"+deviceCode+"'",null);
                if (room!=null){
                    room.setElectric(new BigDecimal((json.getString("power"))));
                    Blade.create(Room.class).update(room);
                }
            } else if (msgType.equals("1021")) {
//                SMS.send(mobile,oldCode,"60");
                //开关门信息
                content = json.getString("content");
                json = JSONObject.parseObject(content);
                Room r = Blade.create(Room.class).findFirstBy("lockNo=#{lockNo}", getData("lockNo", deviceCode));
                if (r==null){
                    return success("收到");
                }

                List<TenantRoom> tr =  Blade.create(TenantRoom.class).findBy(" defence= 1 and roomId = "+r.getId()+" and status=1 AND defenceTime <=DATE_SUB(NOW(),INTERVAL 5 MINUTE);",null);

                for (TenantRoom tenantRoom:tr){
                    Tenant tenant = Blade.create(Tenant.class).findById(tenantRoom.getTenantId());
                    SMS.sendMSG(tenant.getMobile());
                    tenantRoom.setDefence(0);
                    Blade.create(TenantRoom.class).update(tenantRoom);
                }

                Integer tenantId = 0;
                if (json.containsKey("lock_user_code")){
                    String lock = json.getString("lock_user_code").split(",")[0];
                    TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" fingerprint= "+lock+" and roomId="+r.getId()+" ORDER BY id desc ",null);
                    if (tenantRoom!=null){
                        tenantId = tenantRoom.getTenantId();
                    }
                }
                String lock = json.getString("unlock_way");
                OpenHistory openHistory = new OpenHistory();
                openHistory.setCreateDate(new Date());
                openHistory.setRoomId(r.getId());
                openHistory.setMsg(aa);
                openHistory.setType(Integer.valueOf(lock));
                openHistory.setTenantId(tenantId);
                Blade.create(OpenHistory.class).save(openHistory);
            }
        } catch (Exception e) {
            System.out.println("解密异常..");
            e.printStackTrace();
        }
        return success("收到");
    }
}
